<?php
define("UPLOAD_DIR", WWW_ROOT.'files'.DS.'payee');
class PayeesController extends AppController {
    
    public $uses = array('Payee', 'File');
    /**
    * @Method       :beforeFilter
    * @Description  :Parent Before filter calling
    * @access       :public
    * @param        :null
    * @return       :null
    */
    public function beforeFilter(){
        //--------- Directory Creation------------
        if (!is_dir(UPLOAD_DIR)) {
            mkdir(UPLOAD_DIR, 0777);         
        }
        $this->layout = 'home';
        parent::beforeFilter();
    }
    
    /**
    * @Method       :index
    * @Description  :to set up the Lisitng of Service Units
    * @access       :public
    * @param        :null
    * @return       :null
    */
    public function payee_links() {
        
    }
    
    /**
    * @Method       :index
    * @Description  :to set up the Lisitng of Service Units
    * @access       :public
    * @param        :null
    * @return       :null
    */
    public function index() {
        $userId = $this->Auth->User("id");
        $userType = $this->Auth->User('user_type');

        $savecrit = '';

        //criteria array for search
        $crit = array();
        $crit[] = "";

        if (isset($this->data)) {

            if (isset($this->data['Payee']['search_criteria']) && $this->data['Payee']['search_criteria'] != '') {
                $searchCriteriaTerm = trim($this->data['Payee']['search_criteria']);
                //will search with name and abbreviation
                $crit[] = "(Payee.eng_name like '%" . $searchCriteriaTerm . "%')";
                $savecrit .= "search_criteria:" . $searchCriteriaTerm . "/";
            }
        }
        //for passing the values of search conditions in params of paging to next page
        if (count($this->params['named']) > 0) {
            foreach ($this->params['named'] as $paramKey => $paramValue) {
                $savecrit .= $paramKey . ":" . $paramValue . "/";
            }
            if (isset($this->params['named']['search_criteria'])){
                $crit[] = "(ServiceUnit.eng_name like '%" . $this->params['named']['search_criteria'] . "%')";
            }
        }//if
        if (count($crit) > 0) {
            $criteria = implode("1 AND ", $crit);
        } else {
            $criteria = "";
        }

        App::Import("Model", "Payee");
        $this->Payee = new Payee();

        $payeeData = $this->paginate('Payee', array($criteria));

        $this->set('payeeData', $payeeData);

        if ($this->request->is('ajax')) {
            $this->viewPath = 'elements' . DS . 'payees';
            $this->render('list', 'ajax');
        }//if
    }
    
    /**
    * @Method       :adds
    * @Description  :to add a payee
    * @access       :public
    * @param        :null
    * @return       :null
    */
    public function add() {
        if ($this->request->is('post')) {
            $userId = $this->Auth->User("id");
            $userType = $this->Auth->User('user_type');      
            
            $this->Payee->create(); 
            
            $this->request->data['Payee']['recorded_by'] = $userId;
            $this->request->data['Payee']['last_created_by'] = $userId;
            
            App::Import("Model", "File");
            $this->File = new File();

            $this->File->set($this->request->data);
            if ($this->File->validates()) {
                if ($this->Payee->save($this->request->data)) {
                    $payee_id = $this->Payee->getLastInsertID();
                    if(isset($this->request->data['contact_file']) || isset($this->request->data['ids_file'])){
                        $data = array();
                        if (!is_dir(UPLOAD_DIR.DS.$payee_id)) {
                            mkdir(UPLOAD_DIR.DS.$payee_id, 0777);         
                        }
                        if(isset($this->request->data['contact_file'])){
                            foreach($this->request->data['contact_file'] as $contactFiles){
                                $tmp_name = $contactFiles["tmp_name"];
                                $name = $contactFiles["name"];
                                $newFileName = time().'_'.str_replace(" ", "_", $name);

                                if(move_uploaded_file($tmp_name, UPLOAD_DIR.DS.$payee_id.DS.$newFileName)){
                                    $data[]['File'] = array(
                                        'payee_id' => $payee_id,
                                        'file_name' => $name,
                                        'new_file_name' => $newFileName,
                                        'mime_type' => $contactFiles["type"],
                                        'file_size' => $contactFiles["size"],
                                        'type' => 'contact',
                                        'upload_by' => $userId
                                    );
                                }
                            }
                        }
                        if(isset($this->request->data['ids_file'])){
                            foreach($this->request->data['ids_file'] as $contactFiles){
                                $tmp_name = $contactFiles["tmp_name"];
                                $name = $contactFiles["name"];
                                $newFileName = time().'_'.str_replace(" ", "_", $name);

                                if(move_uploaded_file($tmp_name, UPLOAD_DIR.DS.$payee_id.DS.$newFileName)){
                                    $data[]['File'] = array(
                                        'payee_id' => $payee_id,
                                        'file_name' => $name,
                                        'new_file_name' => $newFileName,
                                        'mime_type' => $contactFiles["type"],
                                        'file_size' => $contactFiles["size"],
                                        'type' => 'id',
                                        'upload_by' => $userId
                                    );
                                }
                            }
                        }
                        if($data){
                            $this->File->saveMany($data);
                        }
                    }
                    $msg = __("PAYEE_ADD_SUCCESS", true);
                    $this->Session->setFlash('<div class="totalSuccess">' . $msg . '</div>');
                    return $this->redirect(array('action' => 'index'));
                }
            } else{
                //pr($this->File->validationErrors );
                $msg = __("INVALID_FILE_TYPE", true). ' ' .__("ONLY_PDF_ALLOWED", true);
                $this->Session->setFlash('<div class="totalErrors">' . $msg . '</div>');
            }

            //$msg = __("PAYEE_ADD_FAILURE", true);
	    //$this->Session->setFlash('<div class="totalErrors">' . $msg . '</div>');
            
        }
        $this->set('fileData', array());
    }
    
    /**
    * @Method       :edit
    * @Description  :to edit a payee
    * @access       :public
    * @param        :null
    * @return       :null
    */
    public function edit($id = null) {
        $userId = $this->Auth->User("id");
        $userType = $this->Auth->User('user_type');

        if (!$id) {
            throw new NotFoundException(__('INVALID_PAYEE'));
        }
        $payee = $this->Payee->findById($id);

        if (!$payee) {
            throw new NotFoundException(__('INVALID_PAYEE'));
        }
        $involvedUserId = array();
        if(isset($payee['File'])){
            foreach ($payee['File'] as $files){
                $involvedUserId[] = $files['upload_by'];
            }
        }
        $involvedUserId[] = $payee['Payee']['recorded_by'];
        $involvedUserId[] = $payee['Payee']['last_created_by'];
        $userData = $this->getUserInvolved($involvedUserId);

        if ($this->request->is(array('Payee', 'put'))) {
            $this->Payee->id = $payee_id = $id;
            $this->Payee->validator()->remove('bank_account_no');
            if ($this->Payee->save($this->request->data)) {
                $data = array();
                if (!is_dir(UPLOAD_DIR.DS.$payee_id)) {
                    mkdir(UPLOAD_DIR.DS.$payee_id, 0777);         
                }

                if(isset($this->request->data['contact_file'])){
                    foreach($this->request->data['contact_file'] as $contactFiles){
                        $tmp_name = $contactFiles["tmp_name"];
                        $name = $contactFiles["name"];
                        $newFileName = time().'_'.str_replace(" ", "_", $name);

                        if(move_uploaded_file($tmp_name, UPLOAD_DIR.DS.$payee_id.DS.$newFileName)){
                            $data[]['File'] = array(
                                'payee_id' => $payee_id,
                                'file_name' => $name,
                                'new_file_name' => $newFileName,
                                'mime_type' => $contactFiles["type"],
                                'file_size' => $contactFiles["size"],
                                'type' => 'contact',
                                'upload_by' => $userId
                            );
                        }
                    }
                }
                if(isset($this->request->data['ids_file'])){
                    foreach($this->request->data['ids_file'] as $contactFiles){
                        $tmp_name = $contactFiles["tmp_name"];
                        $name = $contactFiles["name"];
                        $newFileName = time().'_'.str_replace(" ", "_", $name);

                        if(move_uploaded_file($tmp_name, UPLOAD_DIR.DS.$payee_id.DS.$newFileName)){
                            $data[]['File'] = array(
                                'payee_id' => $payee_id,
                                'file_name' => $name,
                                'new_file_name' => $newFileName,
                                'mime_type' => $contactFiles["type"],
                                'file_size' => $contactFiles["size"],
                                'type' => 'id',
                                'upload_by' => $userId
                            );
                        }
                    }
                }
                if($data){
                    $this->File->saveMany($data);
                }
                $msg = __("PAYEE_UPDATE_SUCCESS", true);
                $this->Session->setFlash('<div class="totalSuccess">' . $msg . '</div>');
                return $this->redirect(array('action' => 'index'));
            }
            $msg = __("PAYEE_UPDATE_FAILURE", true);
            $this->Session->setFlash('<div class="totalErrors">' . $msg . '</div>');
        }
        if (!$this->request->data) {
            $this->request->data = $payee;
        }
        
        $this->set('contract_files', $this->getContractFiles());
        $this->set('userData', $userData);
    }
    
    public function getContractFiles(){
        App::Import("Model", "Template");
        $this->Template = new Template();
        $scanned_directory = $this->Template->find('list', array(
                        'fields' => array('Template.id', 'Template.title'), 
                        'conditions' => array('Template.type'  => 'contract')
                    ));
        
        return $scanned_directory;
    }
    
    public function print_contract($id = null){ 

        $this->layout = '';
        $this->autoRender = FALSE;
 
        $this->Payee->recursive = -1;
        $payee = $this->Payee->findById($id);
        if (!$payee) {
            throw new NotFoundException(__('INVALID_PAYEE'));
        }

        $logo = '<img src="'.WWW_ROOT.'img/yot_label.png" alt="test alt attribute" width="238" height="67" border="0" />';
        $search = array('{eng_name}', '{chi_name}', '{payee_id_proof_no}', '{address}', '[logo]');
        $replace = array($payee['Payee']['eng_name'], $payee['Payee']['chi_name'], $payee['Payee']['payee_id_proof_no'], $payee['Payee']['address'], $logo);
        
        if($this->request->data['Payee']['selected_file']){
            App::Import("Model", "Template");
            $this->Template = new Template();
            $template = $this->Template->findById($this->request->data['Payee']['selected_file']);

            $fileContent = $template['Template']['content'];
            $updatedContent = str_replace($search, $replace, $fileContent);
            //$fileName = $payee['Payee']['eng_name'].'_Conract.doc';
            //$fp = fopen($fileName, 'w+');
 
            //$str = $updatedContent;
            
            //fwrite($fp, $str);
            //fclose($fp);
            
            header("Cache-Control: public");
            header("Content-Description: File Transfer");
            header("Content-Disposition: attachment; filename=".str_replace(" ", "_", $payee['Payee']['eng_name']).'.doc');
            header("Content-Type: application/msword"); 
            header("Content-Transfer-Encoding: binary");
            echo $updatedContent;
        }
    }
    
    public function print_contract_old($id = null){ 
        Configure::write('debug', 0);
        $this->layout = '';
        $this->autoRender = FALSE;
 
        $this->Payee->recursive = -1;
        $payee = $this->Payee->findById($id);
        if (!$payee) {
            throw new NotFoundException(__('INVALID_PAYEE'));
        }
        App::import('Vendor', 'TCPDF', array('file' => 'TCPDF'.DS.'tcpdf.php'));
        $pdf = new TCPDF('P', PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
        $pdf->setPrintHeader(false);
        $pdf->setPrintFooter(false);

        $logo = '<img src="'.K_PATH_IMAGES.'yot_label.png" alt="test alt attribute" width="238" height="67" border="0" />';
        $search = array('{eng_name}', '{chi_name}', '{payee_id_proof_no}', '{address}', '[logo]');
        $replace = array($payee['Payee']['eng_name'], $payee['Payee']['chi_name'], $payee['Payee']['payee_id_proof_no'], $payee['Payee']['address'], $logo);
        
        if ($this->request->is(array('Payee', 'put'))) {
            if($this->request->data['Payee']['selected_file']){
                App::Import("Model", "Template");
                $this->Template = new Template();
                $template = $this->Template->findById($this->request->data['Payee']['selected_file']);

                $fileContent = $template['Template']['content'];
                $updatedContent = str_replace($search, $replace, $fileContent);

                // set document information
                $pdf->SetCreator(PDF_CREATOR);
                $pdf->SetAuthor('Admin');
                $pdf->SetTitle('Contract');
                
                $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

                // set margins
                $pdf->SetMargins(PDF_MARGIN_LEFT, 10, PDF_MARGIN_RIGHT);

                // set auto page breaks
                $pdf->SetAutoPageBreak(TRUE, 5);

                // set image scale factor
                $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

                // set some language-dependent strings (optional)
                if (@file_exists(dirname(__FILE__).'/lang/eng.php')) {
                    require_once(dirname(__FILE__).'/lang/eng.php');
                    $pdf->setLanguageArray($l);
                }

                // ---------------------------------------------------------

                // set default font subsetting mode
                $pdf->setFontSubsetting(true);

                // Set font
                // dejavusans is a UTF-8 Unicode font, if you only need to
                // print standard ASCII chars, you can use core fonts like
                // helvetica or times to reduce file size.
                $pdf->SetFont('kozminproregular', '', 9, '', true);
//echo $updatedContent;
//die();
                // Add a page
                // This method has several options, check the source code documentation for more information.
                $pdf->AddPage();
                $pdf->writeHTML($updatedContent, true, false, true, false, '');
                $pdf->lastPage();
                $pdf->Output($payee['Payee']['eng_name'].'_Conract.pdf', 'D');
            }
        }
    }

    public function getUserInvolved($userId = null){
        App::Import("Model", "User");
        $this->User = new User();
        $userId = array_unique($userId);
        return $this->User->find('list', array('fields' => array('User.id', 'User.e_name'), 'conditions' => array('User.id' => $userId)));
    }
    
    /**
    * @Method       :delete_payee
    * @Description  :to delete a payee 
    * @access       :public
    * @param        :null
    * @return       :null
    */
    public function delete_payee($payee_id = null){
        $this->disableCache();
        $this->autoRender = false;
        $this->layout = '';
        
        $payeeDetails = $this->Payee->findById($payee_id);
        
        $payee_id_proof_no = $payeeDetails['Payee']['payee_id_proof_no'];
        
        //--- delete related Payables---------
        App::Import("Model", "Payable");
        $this->Payable = new Payable();
        $this->Payable->recursive = -1;
        $payables = $this->Payable->find('list', 
                        array(
                            'conditions' => array('Payable.payee_id_proof_no' => $payee_id_proof_no),
                            'fields' => array('Payable.id')
                        )
                    );
        
        $payableCondition = array('Payable.id' => $payables);
        $this->Payable->deleteAll($payableCondition, FALSE);
        
        //--- delete related Files---------
        if(!empty($payeeDetails['File'])){
            $fileId = array();
            foreach ($payeeDetails['File'] as $fileDetail) {
                $fileWithPath = UPLOAD_DIR . DS . $payee_id . DS . $fileDetail['new_file_name'];
                if (file_exists($fileWithPath)) {
                    unlink($fileWithPath);
                }
                $fileId[] = $fileDetail['id'];
            }
            //chmod(UPLOAD_DIR . DS . $payee_id, 0777);
            //unlink(UPLOAD_DIR . DS . $payee_id);
            $fileCondition = array('File.id' => $fileId);
            $this->File->deleteAll($fileCondition, FALSE);
        }
        
        //--- delete Payee---------
        $payeeCondition = array('Payee.id' => $payee_id);
        $this->Payee->delete($payeeCondition, FALSE);
        
        
        //--- Pagination---------
        $criteria = "";
        $payeeData = $this->paginate('Payee', array($criteria));
        $this->set('payeeData', $payeeData);

        if ($this->request->is('ajax')) {
            $this->viewPath = 'elements' . DS . 'payees';
            $this->render('list', 'ajax');
        }//if
    }
    
    /**
    * @Method       :delete
    * @Description  :to delete file attached to profile
    * @access       :public
    * @param        :null
    * @return       :null
    */
    public function delete($id= null, $payeeId = null, $type = null) {

        $this->autoRender = false;
        $this->layout = '';
        
        App::Import("Model", "File");
        $this->File = new File();
        $fileDetails = $this->File->findById($id);
        
        $fileWithPath = UPLOAD_DIR.DS.$payeeId.DS.$fileDetails['File']['new_file_name'];
        
        $condition = array('File.id' => $id);
        if($this->File->delete($condition, FALSE)){
            if(file_exists($fileWithPath)){
                unlink($fileWithPath);
            }
        }
        
        $payee = $this->Payee->findById($payeeId);
        $involvedUserId = array();
        if(isset($payee['File'])){
            foreach ($payee['File'] as $files){
                $involvedUserId[] = $files['upload_by'];
            }
        }
        $involvedUserId[] = $payee['Payee']['recorded_by'];
        $involvedUserId[] = $payee['Payee']['last_created_by'];
        $userData = $this->getUserInvolved($involvedUserId);
        $this->request->data = $payee;
        $this->set('userData', $userData);
        
        if ($this->request->is('ajax')) {
            $this->viewPath = 'elements' . DS . 'payees';
            $this->render($type, 'ajax');
        }//if
    }
    
    /**
    * @Method       :download_file
    * @Description  :to delete temp file upload
    * @access       :public
    * @param        :null
    * @return       :null
    */
    
    public function download_file($file_id = null){
        $this->autoRender = false;
        $this->layout = '';
        
        App::Import("Model", "File");
        $this->File = new File();
        $fileDetails = $this->File->findById($file_id);
        
        
        $file_extension = strtolower(substr(strrchr($fileDetails['File']['new_file_name'],"."),1));
        switch( $file_extension ){
            case "pdf": $ctype="application/pdf"; break;
            case "exe": $ctype="application/octet-stream"; break;
            case "zip": $ctype="application/zip"; break;
            case "doc": $ctype="application/msword"; break;
            case "xls": $ctype="application/vnd.ms-excel"; break;
            case "ppt": $ctype="application/vnd.ms-powerpoint"; break;
            case "gif": $ctype="image/gif"; break;
            case "png": $ctype="image/png"; break;
            case "jpeg":
            case "jpg": $ctype="image/jpg"; break;
            default: $ctype="application/force-download";
        }
        
        $fileNameNew = UPLOAD_DIR.DS.$fileDetails['File']['payee_id'].DS.$fileDetails['File']['new_file_name'];
        $fileName = $fileDetails['File']['file_name'];
        header("Pragma: public"); // required
        header("Expires: 0");
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header("Cache-Control: private",false); // required for certain browsers 
        header("Content-Type: $ctype");
        // change, added quotes to allow spaces in filenames, by Rajkumar Singh
        header("Content-Disposition: attachment; filename=\"".basename($fileName)."\";" );
        header("Content-Transfer-Encoding: binary");
        header("Content-Length: ".filesize($fileNameNew));
        readfile($fileNameNew);
        exit();
    }
    
    /**
    * @Method       :admin_index
    * @Description  :to set up the Lisitng of Service Units
    * @access       :public
    * @param        :null
    * @return       :null
    */
    public function admin_payee_links() {

    }
    
    /**
    * @Method       :admin_index
    * @Description  :to set up the Lisitng of Service Units
    * @access       :public
    * @param        :null
    * @return       :null
    */
    public function admin_index() {
        $userId = $this->Auth->User("id");
        $userType = $this->Auth->User('user_type');

        $savecrit = '';

        //criteria array for search
        $crit = array();
        $crit[] = "";

        if (isset($this->data)) {

            if (isset($this->data['Payee']['search_criteria']) && $this->data['Payee']['search_criteria'] != '') {
                $searchCriteriaTerm = trim($this->data['Payee']['search_criteria']);
                //will search with name and abbreviation
                $crit[] = "(Payee.eng_name like '%" . $searchCriteriaTerm . "%')";
                $savecrit .= "search_criteria:" . $searchCriteriaTerm . "/";
            }
        }
        //for passing the values of search conditions in params of paging to next page
        if (count($this->params['named']) > 0) {
            foreach ($this->params['named'] as $paramKey => $paramValue) {
                $savecrit .= $paramKey . ":" . $paramValue . "/";
            }
            if (isset($this->params['named']['search_criteria'])){
                $crit[] = "(ServiceUnit.eng_name like '%" . $this->params['named']['search_criteria'] . "%')";
            }
        }//if
        if (count($crit) > 0) {
            $criteria = implode("1 AND ", $crit);
        } else {
            $criteria = "";
        }

        App::Import("Model", "Payee");
        $this->Payee = new Payee();

        $payeeData = $this->paginate('Payee', array($criteria));

        $this->set('payeeData', $payeeData);

        if ($this->request->is('ajax')) {
            $this->viewPath = 'elements' . DS . 'payees';
            $this->render('admin_list', 'ajax');
        }//if
    }
    
    /**
    * @Method       :edit
    * @Description  :to edit a payee
    * @access       :public
    * @param        :null
    * @return       :null
    */
    public function admin_edit($id = null) {
        $userId = $this->Auth->User("id");
        $userType = $this->Auth->User('user_type');

        if (!$id) {
            throw new NotFoundException(__('INVALID_PAYEE'));
        }
        $payee = $this->Payee->findById($id);

        if (!$payee) {
            throw new NotFoundException(__('INVALID_PAYEE'));
        }
        $involvedUserId = array();
        if(isset($payee['File'])){
            foreach ($payee['File'] as $files){
                $involvedUserId[] = $files['upload_by'];
            }
        }
        $involvedUserId[] = $payee['Payee']['recorded_by'];
        $involvedUserId[] = $payee['Payee']['last_created_by'];
        $userData = $this->getUserInvolved($involvedUserId);

        if ($this->request->is(array('Payee', 'put'))) {
            $this->Payee->id = $payee_id = $id;
            if ($this->Payee->save($this->request->data)) {
                $data = array();
                if (!is_dir(UPLOAD_DIR.DS.$payee_id)) {
                    mkdir(UPLOAD_DIR.DS.$payee_id, 0777);         
                }

                if(isset($this->request->data['contact_file'])){
                    foreach($this->request->data['contact_file'] as $contactFiles){
                        $tmp_name = $contactFiles["tmp_name"];
                        $name = $contactFiles["name"];
                        $newFileName = time().'_'.str_replace(" ", "_", $name);

                        if(move_uploaded_file($tmp_name, UPLOAD_DIR.DS.$payee_id.DS.$newFileName)){
                            $data[]['File'] = array(
                                'payee_id' => $payee_id,
                                'file_name' => $name,
                                'new_file_name' => $newFileName,
                                'mime_type' => $contactFiles["type"],
                                'file_size' => $contactFiles["size"],
                                'type' => 'contact',
                                'upload_by' => $userId
                            );
                        }
                    }
                }
                if(isset($this->request->data['ids_file'])){
                    foreach($this->request->data['ids_file'] as $contactFiles){
                        $tmp_name = $contactFiles["tmp_name"];
                        $name = $contactFiles["name"];
                        $newFileName = time().'_'.str_replace(" ", "_", $name);

                        if(move_uploaded_file($tmp_name, UPLOAD_DIR.DS.$payee_id.DS.$newFileName)){
                            $data[]['File'] = array(
                                'payee_id' => $payee_id,
                                'file_name' => $name,
                                'new_file_name' => $newFileName,
                                'mime_type' => $contactFiles["type"],
                                'file_size' => $contactFiles["size"],
                                'type' => 'id',
                                'upload_by' => $userId
                            );
                        }
                    }
                }
                if($data){
                    $this->File->saveMany($data);
                }
                $msg = __("PAYEE_UPDATE_SUCCESS", true);
                $this->Session->setFlash('<div class="totalSuccess">' . $msg . '</div>');
                return $this->redirect(array('action' => 'admin_index'));
            }
            $msg = __("PAYEE_UPDATE_FAILURE", true);
            $this->Session->setFlash('<div class="totalErrors">' . $msg . '</div>');
        }
        if (!$this->request->data) {
            $this->request->data = $payee;
        }
        $this->set('userData', $userData);
    }
    
    /**
    * @Method       :delete_payee
    * @Description  :to delete a payee 
    * @access       :public
    * @param        :null
    * @return       :null
    */
    public function admin_delete_payee($payee_id = null){
        $this->disableCache();
        $this->autoRender = false;
        $this->layout = '';
        
        $payeeDetails = $this->Payee->findById($payee_id);
        
        $payee_id_proof_no = $payeeDetails['Payee']['payee_id_proof_no'];
        
        //--- delete related Payables---------
        App::Import("Model", "Payable");
        $this->Payable = new Payable();
        $this->Payable->recursive = -1;
        $payables = $this->Payable->find('list', 
                        array(
                            'conditions' => array('Payable.payee_id_proof_no' => $payee_id_proof_no),
                            'fields' => array('Payable.id')
                        )
                    );
        
        $payableCondition = array('Payable.id' => $payables);
        $this->Payable->deleteAll($payableCondition, FALSE);
        
        //--- delete related Files---------
        if(!empty($payeeDetails['File'])){
            $fileId = array();
            foreach ($payeeDetails['File'] as $fileDetail) {
                $fileWithPath = UPLOAD_DIR . DS . $payee_id . DS . $fileDetail['new_file_name'];
                if (file_exists($fileWithPath)) {
                    unlink($fileWithPath);
                }
                $fileId[] = $fileDetail['id'];
            }
            //chmod(UPLOAD_DIR . DS . $payee_id, 0777);
            //unlink(UPLOAD_DIR . DS . $payee_id);
            $fileCondition = array('File.id' => $fileId);
            $this->File->deleteAll($fileCondition, FALSE);
        }
        
        //--- delete Payee---------
        $payeeCondition = array('Payee.id' => $payee_id);
        $this->Payee->delete($payeeCondition, FALSE);
        
        
        //--- Pagination---------
        $criteria = "";
        $payeeData = $this->paginate('Payee', array($criteria));
        $this->set('payeeData', $payeeData);

        if ($this->request->is('ajax')) {
            $this->viewPath = 'elements' . DS . 'payees';
            $this->render('admin_list', 'ajax');
        }//if
    }
}